package com.zoespeer.food_delivery_comment_api.util;

import com.zoespeer.food_delivery_comment_api.common.ApiResponse;
import com.zoespeer.food_delivery_comment_api.common.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;

public class TokenParseUtil {

    /**
     * 解析Token并返回字符串类型用户ID（用于查询评论等场景）
     */
    public static ApiResponse<String> parseUserIdAsString(String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return ApiResponse.error("无效的Token格式，请使用Bearer Token");
        }

        String actualToken = authorization.substring(7).trim();
        String userId;

        try {
            userId = JwtUtil.getUserIdFromTokenAsString(actualToken);
        } catch (ExpiredJwtException e) {
            return ApiResponse.error("Token已过期，请重新登录");
        } catch (JwtException e) {
            return ApiResponse.error("无效的Token：" + e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("Token解析失败：" + e.getMessage());
        }

        return ApiResponse.success(userId, "Token解析成功");
    }

    /**
     * 解析Token并返回Integer类型用户ID（用于删除评论等场景）
     */
    public static ApiResponse<Integer> parseUserIdAsInt(String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return ApiResponse.error("无效的Token格式，请使用Bearer Token");
        }

        String actualToken = authorization.substring(7).trim();
        Integer userId;

        try {
            userId = JwtUtil.getUserIdFromToken(actualToken);
        } catch (ExpiredJwtException e) {
            return ApiResponse.error("Token已过期，请重新登录");
        } catch (JwtException e) {
            return ApiResponse.error("无效的Token：" + e.getMessage());
        } catch (NumberFormatException e) {
            return ApiResponse.error("Token中用户ID格式错误，需为数字类型");
        } catch (Exception e) {
            return ApiResponse.error("Token解析失败：" + e.getMessage());
        }

        return ApiResponse.success(userId, "Token解析成功");
    }
}